import React, { PureComponent } from 'react';
import { Button, Card, message, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import router from 'umi/router';
import { connect } from 'dva';
import { filterAuth } from '@/support/common';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import { publishStatus, channelCdList } from './variable';
import { FormInstance } from 'antd/lib/form';

interface pageInitType {
  current: number;
  pageSize: number;
}
interface stateType {
  formValues: any;
  sendSelect: Array<sendSelectType>;
}
interface sendSelectType {
  value: string;
  label: string;
  [propName: string]: any;
}

const mapStateToProps = (state: any) => {
  return {
    messageTemplate: state.messageTemplate,
    loading: state.loading.effects['messageTemplate/getFetchPage'],
    permissions: state?.menu?.permissions,
  };
};
class index extends PureComponent<any, stateType> {
  // 数据
  state = {
    formValues: {},
    sendSelect: [],
  };
  pageInit: pageInitType = {
    current: 1,
    pageSize: 10,
  };
  searchRef: any = '';

  componentDidMount() {
    this.getList();
  }
  // 新增
  handleAdd() {
    router.push('/messageCenter/messageTemplateManagement/messageTemplate_doAdd');
  }
  getList = (obj: any = {}) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'messageTemplate/getFetchPage',
      payload: { url: '/message/template/findByPage', ...this.pageInit, ...formValues, ...obj },
    });
  };
  //
  // 渲染
  render() {
    const {
      messageTemplate: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
      permissions,
      dispatch,
    } = this.props;

    const { formValues, sendSelect } = this.state;

    const searchItems = [
      {
        type: 'input',
        title: '模板编号',
        key: 'msgCd',
      },
      {
        type: 'input',
        title: '模板名称',
        key: 'tplTitle',
      },
      {
        type: 'select',
        title: '渠道类型',
        key: 'channelCd',
        selectOptions: channelCdList,
        onChange: (val: string) => {
          const { dispatch } = this.props;
          dispatch({
            type: 'messageTemplate/getData',
            payload: { url: '/message/template/findSenderIdByChannelCd', channelCd: parseInt(val) },
            callback: (res: any) => {
              const arr = res.data;
              let sendCd = '';
              arr.forEach((e: sendSelectType) => {
                if (!sendCd) {
                  const list = Object.keys(e);
                  sendCd = list.find(e => e.includes('Cd')) as string;
                }
                e.value = e[sendCd];
                e.label = e[sendCd];
              });

              this.searchRef.current.setFieldsValue({
                senderId: null,
              });

              this.setState({
                sendSelect: arr,
              });
            },
          });
        },
      },
      {
        type: 'select',
        title: '渠道发送方',
        key: 'senderId',
        selectOptions: sendSelect,
      },
      {
        type: 'select',
        title: '发布状态',
        key: 'approvalStatus',
        selectOptions: publishStatus,
      },
    ];

    // 取消发布
    const columns = [
      {
        title: '模板编号',
        dataIndex: 'msgCd',
      },
      {
        title: '模板名称',
        dataIndex: 'tplTitle',
      },
      {
        title: '渠道类型',
        dataIndex: 'defaultPushChannel',
        render: (txt: number) => {
          return channelCdList.find(e => e.value == txt)?.label;
        },
      },
      {
        title: '渠道发送方',
        dataIndex: 'defaultMoreOptions',
        render: (obj: any) => {
          return obj?.defaultSenderCd;
        },
      },
      {
        title: '发布状态',
        dataIndex: 'approvalStatus',
        render: (txt: number) => {
          return publishStatus.find(e => e.value == txt)?.label;
        },
      },
      {
        title: '发布人',
        dataIndex: 'updateBy',
      },
      {
        title: '发布时间',
        dataIndex: 'createDate',
      },
      {
        title: '发布更新时间',
        dataIndex: 'updateDate',
      },
      {
        fixed: 'right',
        title: '操作',
        dataIndex: '操作',
        width: 250,
        render: (text: any, record: any) => {
          const { approvalStatus, id, msgCd, projectId } = record;
          const bool = approvalStatus == 3;
          // 发布
          const doPublish = () => {
            doPublishFn({
              text: '发布成功',
              publishStatus: 5,
            });
          };
          // 取消发布
          const doCancelFn = () => {
            doPublishFn({
              text: '取消发布成功',
              publishStatus: 3,
            });
          };
          const doPublishFn = (obj: any) => {
            dispatch({
              type: 'messageTemplate/getDataWithRes',
              payload: {
                url: '/message/template/updateTemplateStatus',
                msgCd,
                projectId,
                publishStatus: obj.publishStatus,
              },
              callback: (response: any) => {
                if (response.statusCode === '0') {
                  // 删除成功
                  message.success(obj.text);
                  // 请求数据
                  this.getList();
                } else {
                  message.error(response.statusMessage);
                }
              },
            });
          };
          // 编辑
          const onEditFn = () => {
            router.push(
              `/messageCenter/messageTemplateManagement/messageTemplate_doEdit?msgCd=${msgCd}&projectId=${projectId}`,
            );
          };
          // 删除
          const doDelFn = () => {
            dispatch({
              type: 'messageTemplate/getDataWithRes',
              payload: { url: '/message/template/deleteTemplate', id },
              callback: (response: any) => {
                if (response.statusCode === '0') {
                  // 删除成功
                  message.success('删除成功');
                  // 请求数据
                  this.getList();
                } else {
                  message.error(response.statusMessage);
                }
              },
            });
          };
          // 查看
          const onShowFn = () => {
            router.push(
              `/messageCenter/messageTemplateManagement/messageTemplate_show?msgCd=${msgCd}&projectId=${projectId}`,
            );
          };
          // 手动发送
          const onSendFn = () => {
            const str = JSON.stringify(record);
            sessionStorage.setItem('templateData', str);
            router.push(`/messageCenter/messageTemplateManagement/messageTemplate_doSend`);
          };
          const btns = bool
            ? [
                {
                  title: '发布',
                  key: 'doPublish',
                  auth: 'messageTemplate_doPublish',
                  Popconfirm: true,
                  message: '是否确认发布？',
                  onConfirm: doPublish,
                },
                {
                  title: '编辑',
                  key: 'edit',
                  auth: 'messageTemplate_doAdd',
                  onConfirm: onEditFn,
                },
                {
                  title: '删除',
                  key: 'doDel',
                  auth: 'messageTemplate_doDel',
                  onConfirm: doDelFn,
                  Popconfirm: true,
                  message: '是否确认删除？',
                },
                {
                  title: '查看',
                  key: 'show',
                  auth: 'messageTemplate_show',
                  onConfirm: onShowFn,
                },
              ]
            : [
                {
                  title: '取消发布',
                  key: 'doPublish',
                  auth: 'messageTemplate_doPublish',
                  Popconfirm: true,
                  message: '是否确认取消发布？',
                  onConfirm: doCancelFn,
                },
                {
                  title: '查看',
                  key: 'show',
                  auth: 'messageTemplate_show',
                  onConfirm: onShowFn,
                },
                {
                  title: '手动发送',
                  key: 'doSend',
                  auth: 'messageTemplate_doSend',
                  onConfirm: onSendFn,
                },
              ];

          return <PateoAuthButtons btns={btns} max="4" pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onChange: (val: any) => {
        const params = { ...formValues, ...val };
        this.getList(params);
        this.setState({
          formValues: params,
        });
      },
    };

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(ref: FormInstance) => {
              this.searchRef = ref;
            }}
            searchItems={searchItems}
            fetchParams={{
              type: 'messageTemplate/getFetchPage',
              url: '/message/template/findByPage',
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: { ...formValues, ...val },
              });
            }}
            handleFormReset={() => {
              this.setState({
                formValues: {},
              });
            }}
            handleFieldsValue={(val: any) => {
              return { ...val, ...this.pageInit };
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('messageTemplate_doAdd', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增
              </Button>
            </div>
          ) : null}
          {/* <PateoTable tableProps={tableProps} /> */}
          <Table className={styles.my_table} size="small" {...tableProps} />
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
